<?php


namespace app\admin\controller;

use app\logic\DataHelper;
use app\logic\MenuHelper;
use think\facade\Cache;
use think\facade\View;
use think\helper\Str;

class Common extends Base
{
    public function upload_pic() {

        try {
            ob_clean();

            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('file');
            // 移动到框架应用根目录/public/uploads/ 目录下
            if ($file) {
                $fileType = $file->getOriginalMime();
                $name = $file->getOriginalName();
                $size = $_FILES['file']['size'];
                $ext = strtolower($file->getOriginalExtension());
                $typelist = array("application/octet-stream", "image/png", "image/jpeg", "image/gif");
                $extlist = array("jpg", "jpeg", 'png', 'gif');
                $tmppath = $file->getRealPath();
                $md5 = md5_file($tmppath);

                //从数据库里找，找到就返回
                $dbentry = DataHelper::find('tb_user_files', "md5='$md5'");
                if (!empty($dbentry)) {
                    return json([ 'code' => 0, 'msg' => '成功', 'data' => [
                        'url' => $dbentry['file_url'],
                        'src' => $dbentry['file_url']
                    ] ]);
                }


                $dt = Date('Ymd', time());

                $save_path = ROOT_PATH . 'public/img/' . $dt;
                if (!file_exists($save_path)) {
                    mkdir($save_path, 0777, true);
                }

                $filename = time().rand(10000, 99999).'.'.$file->extension();
                if (empty($info))
                    $info = $file->move($save_path, $filename);

                $url = SITE_HOST.'/img/' . $dt . '/' . $filename;


                if ($url) {

                    DataHelper::add('tb_user_files', [
                        'file_name' => $name,
                        'file_ext' => $ext,
                        'file_url' => $url,
                        'md5' => $md5,
                        'create_time' => time_now()
                    ]);


                    return json([
                        'code' => 0,
                        'msg' => '成功',
                        'data' => [
                            'url' => $url,
                            'src' => $url
                        ]
                    ]);


                }else{

                    return json([
                        'code' => 0,
                        'msg' => '成功',
                        'data' => [
                            'url' => '上传失败：' . $file->getError()
                        ]
                    ]);
                }
            }
        } catch (\Exception $ex) {
            throw $ex;
            //return api_return(-1, $ex->getMessage());
        }


    }
}